<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thunk函数</title>
</head>
<body>
    <h1>Thunk函数</h1>
    <h2>将多参数函数转换成单参数的版本</h2>

    <script>
        // 基本的Thunk函数转换
        function thunkify(fn) {
            return function(...args) {
                return function(callback) {
                    args.push(callback);
                    return fn.apply(this, args);
                }
            }
        }

        // 示例：读取文件
        function readFile(filename, encoding, callback) {
            setTimeout(() => {
                callback(null, `${filename}的内容`);
            }, 1000);
        }

        const thunkReadFile = thunkify(readFile);
        const readFileThunk = thunkReadFile('file.txt', 'utf8');
        readFileThunk((err, data) => {
            if (err) throw err;
            console.log(data);
        });

        // Thunk函数与Generator函数的结合
        function* gen() {
            const r1 = yield thunkReadFile('file1.txt', 'utf8');
            console.log(r1);
            const r2 = yield thunkReadFile('file2.txt', 'utf8');
            console.log(r2);
        }

        // 手动执行
        const g = gen();
        const r1 = g.next();
        r1.value((err, data) => {
            if (err) throw err;
            const r2 = g.next(data);
            r2.value((err, data) => {
                if (err) throw err;
                g.next(data);
            });
        });

        // 自动执行
        function run(fn) {
            const gen = fn();

            function next(err, data) {
                const result = gen.next(data);
                if (result.done) return;
                result.value(next);
            }

            next();
        }

        run(gen);
    </script>
</body>
</html> 